package yxy.game.pm2.command.conquest;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.BattleMessage;
import yxy.game.pm2.message.ConquestMessage;
import yxy.game.pm2.module.conquest.ConquestHandle;

import java.util.Date;

/**
 * 征战 挑战敌将战斗开始
 */
@MessageType(proto = Command.ConquestEnemyExecute, classtype = ConquestMessage.ConquestEnemyExecuteRequest.class)
public class CMD_ConquestEnemyExecute extends Command<ConquestMessage.ConquestEnemyExecuteRequest> {

    @Override
    public void execute(MessageSource messageSource, ConquestMessage.ConquestEnemyExecuteRequest request) {
        Date date1 = new Date();

        ConquestMessage.ConquestEnemyExecuteResponse.Builder response = ConquestMessage.ConquestEnemyExecuteResponse.newBuilder();

        try {
            String playerCode = messageSource.getTag();
            BattleMessage.BattleExecuteRequest battleReq = request.getBattleReq();
            ConquestHandle handle = new ConquestHandle();
            if (handle.isBattling(playerCode)) {
                send(messageSource, response, Result.BattleIsRunning);// 还有正在进行中的战斗
                return;
            }

            response.setBattleResp(handle.battleResponseExecute(playerCode, battleReq));
            send(messageSource, response, Result.Success);
        } catch (Exception e) {
            e.printStackTrace();
            send(messageSource, response, Result.DataError);
        }

        Date date2 = new Date();
        System.out.println("CMD_ConquestEnemyExecute:" + (date2.getTime() - date1.getTime()));
    }

    private void send(MessageSource messageSource, ConquestMessage.ConquestEnemyExecuteResponse.Builder response, Result result) {
        response.setResult(result.packResult());
        MessageEmitterHandler.getInstance().send(messageSource, response.build());
    }
}